package com.nettest.service.usermanage;

import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nettest.bean.BaseCriteriaVo;
import com.nettest.bean.usermanage.UserCriteriaVo;
import com.nettest.dao.usermanage.UserProfileDao;
import com.nettest.entity.BaseEntity;
import com.nettest.entity.UserProfile;

@Service
@Transactional
public class UserProfileService {
	private UserProfileDao userProfileDao;

	public List<?> queryByCriteria(BaseCriteriaVo criteriaVo) throws Exception {
		UserCriteriaVo vo = (UserCriteriaVo)criteriaVo;
		
		Set<Criterion> set = getCriteriaSet(criteriaVo);		
		String order = criteriaVo.getDescOrAsc();
		Set<Order> orderSet = new HashSet<Order>();
		if (order != null) {
			if ("ASC".equalsIgnoreCase(order)) {
				orderSet.add(Order.asc(criteriaVo.getDescOrAsc()));
			} else {
				orderSet.add(Order.desc(criteriaVo.getDescOrAsc()));
			}
		}
		
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(UserProfile.class);
		
		for (Criterion o : set) {
			detachedCriteria.add(o);
		}
		if(vo.getRoleId() != null) {
			detachedCriteria.createAlias("role", "r");
			detachedCriteria.add(Restrictions.eq("r.id",vo.getRoleId()));
		}
		for (Order o : orderSet) {
			detachedCriteria.addOrder(o);
		}
		
		List<?> result = userProfileDao.query(detachedCriteria,
				criteriaVo.getFirstResult(), criteriaVo.getMaxResults());
		return result;
	}

	public BaseEntity save(BaseEntity entity) throws Exception {
		return userProfileDao.save((UserProfile)entity);
	}

	public void delete(Long id) throws Exception {
		userProfileDao.delete(id);
	}

	public List<?> executeQuery(String sql) throws Exception {
		return userProfileDao.findBySql(sql);
	}

	public int totalSize(BaseCriteriaVo criteriaVo) throws Exception {
		Set<Criterion> set = getCriteriaSet(criteriaVo);
		return userProfileDao.totalSize(set);
	}

	public UserProfile get(Serializable id) throws Exception {
		return userProfileDao.get(id);
	}
	
	protected Set<Criterion> getCriteriaSet(BaseCriteriaVo criteriaVo) {
		Set<Criterion> set = new HashSet<Criterion>();
		UserCriteriaVo vo = (UserCriteriaVo)criteriaVo;
		if(vo.getUserName() != null) {
			set.add(Restrictions.ilike("userName",vo.getUserName(),MatchMode.ANYWHERE));
		} 
		if(vo.getEmail() != null) {
			set.add(Restrictions.ilike("email",vo.getEmail(),MatchMode.ANYWHERE));
		}		
		return set;
	}
}
